package com.chatim.nonamechatim.config;

import com.chatim.nonamechatim.pojo.User;
import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.http.MediaType;
import org.springframework.security.authentication.AuthenticationServiceException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import java.io.IOException;
public class LoginFilter extends UsernamePasswordAuthenticationFilter {

    @Override
    public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException {
        // 确保进入该过滤器中的请求是 POST 请求
        if (!request.getMethod().equals("POST")) {
            throw new AuthenticationServiceException("Authentication method not supported:"
                    + request.getMethod());
        }
        // 根据请求的 content-type 来判断参数是 JSON 格式的还是 key/value 格式
        if (request.getContentType().equalsIgnoreCase(MediaType.APPLICATION_JSON_VALUE)) {
            try {
                // 利用 jackson 提供的 ObjectMapper 工具将输入流转换为 Map 对象
                User userInfo = new ObjectMapper().readValue(request.getInputStream(), User.class);
                // 提取用户名密码信息
                String username = userInfo.getUsername();
                username = username != null ? username.trim() : "";
                String password = userInfo.getPassword();
                password = password != null ? password : "";
                // 构造 UsernamePasswordAuthenticationToken 对象
                UsernamePasswordAuthenticationToken authRequest =
                        new UsernamePasswordAuthenticationToken(username, password);
                setDetails(request, authRequest);
                // 调用 authenticate 认证
                return this.getAuthenticationManager()
                        .authenticate(authRequest);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        // key/value 格式的，那直接调用父类的 attemptAuthentication 方法处理
        return super.attemptAuthentication(request, response);
    }
}
